//import data from './data.json';
import fs from 'fs';

export default {
  'GET /api/data': (_, response) => {
    let data = JSON.parse(fs.readFileSync('./mock/data.json'));
    response.send(data);
  },

  'GET /api/lists': (_, response) => {
    let data = JSON.parse(fs.readFileSync('./mock/data.json'));
    response.send(data);
  },

  'GET /api/delList/:key': (request, response) => {
    const key = request.params.key;
    let data = JSON.parse(fs.readFileSync('./mock/data.json'));
    data = data.filter((list) => parseInt(list.key) !== parseInt(key));
    fs.writeFileSync('./mock/data.json', JSON.stringify(data));

    response.send('ok');
  },

  'POST /api/update': (request, response) => {
    const { employee } = request.body;
    //let lists = data;
    let data = JSON.parse(fs.readFileSync('./mock/data.json'));
    data = data.map((e) => (e.key === employee.key ? employee : e));
    fs.writeFileSync('./mock/data.json', JSON.stringify(data));

    response.send('ok');
  },

  'POST /api/add': (request, response) => {
    const { employee } = request.body;
    let data = JSON.parse(fs.readFileSync('./mock/data.json'));
    let key = 0;
    for (let i = 0; i < data.length; i++) {
      if (data[i].key > key) {
        key = data[i].key;
      }
    }
    employee.key = parseInt(key) + 1;
    employee.tags = [];
    data.push(employee);
    fs.writeFileSync('./mock/data.json', JSON.stringify(data));
    response.send(employee);
  },
};
